﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace 聊天室客户端
{
    public partial class Form1 : Form
    {
        private Socket sk;
        private int ListIndex;
        private List<String> skList=new List<String>();
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 编辑信息发送给服务器
        /// #@0@! 代表发送的文本信息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Textbutton_Click(object sender, EventArgs e)
        {
            String text = "#@0@!"+PrinttextBox.Text +"给"+ skList[ListIndex];
            byte[] by = Encoding.UTF8.GetBytes(text);
            sk.Send(by);
            SpeaktextBox.Text += "我：" + PrinttextBox.Text+"\t发送给" + skList[ListIndex] + "\r\n";
        }
        /// <summary>
        /// 客户端启动自动连入客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 创建客户端 相互通信 并在服务器留痕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                sk = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse("10.193.3.112");
                IPEndPoint point = new IPEndPoint(ip, 50021);
                Thread.Sleep(1000);
                //服务器地址
                sk.Connect(point);
                
                MessageBox.Show("服务器连接成功");
                Thread th = new Thread(listenText);
                th.IsBackground = true;
                th.Start(sk);

            }
            catch
            {
                MessageBox.Show("服务器连接失败");
            }
        }

        /// <summary>
        /// 循环接收信息
        /// 0 代表发送的文本信息
        /// 1 代表发送的文件
        /// 2 代表发送的震动
        /// </summary>
        /// <param name="sk"></param>
        private void listenText(object sk)
        {
            try
            {
                Socket sks = sk as Socket;
                while (true)
                {
                    //设置一次接收的字符串数
                    byte[] bt = new byte[1024 * 1024 * 5];
                    //接收的数据
                    int r = sks.Receive(bt);
                    if (r == 0) return;
                    String text = Encoding.UTF8.GetString(bt, 0, r);
                    if (bt[0] == 3)
                    {
                        SpeaktextBox.Text += "\r\n" + "接收文件";
                        SaveFileDialog SFD = new SaveFileDialog();
                        SFD.InitialDirectory = @"D:\C#project";
                        SFD.Title = "请选择要传输的文件";
                        SFD.Filter = "所有文件|*.*"; 
                        SFD.ShowDialog(this);
                        String filepath = SFD.FileName;
                        using (FileStream fs =new FileStream(filepath,FileMode.Create,FileAccess.Write)) {
                            fs.Write(bt,0,r);
                        }
                        MessageBox.Show("保存成功");
                    }
                    if (text.IndexOf("：") >= 0) {
                        if (text.IndexOf("#@0@!") > 0)
                        {
                            SpeaktextBox.Text += "\r\n" + text;
                        } else if (text.IndexOf("#@2@!") > 0) {
                            Zhendong();
                            SpeaktextBox.Text += "\r\n" + text+"发来震动" + "\r\n" ;
                        } 
                        continue;
                    } 
                    String[] text1 = text.Split("\r\n".ToCharArray(),StringSplitOptions.RemoveEmptyEntries);
                    foreach (String s in text1)
                    {
                      
                        listBox1.Items.Add(s);
                        foreach (String str in text1) {
                            if (!skList.Contains(s)) skList.Add(s);
                            else break;
                        }
                        
                    }
                    
                    
                }
            }
            catch { }

        }
        /// <summary>
        /// 清除随时更新的客户端列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            listBox1.Items.Clear() ;
        }
        /// <summary>
        /// 赋值给当前选择的客户端
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            ListIndex = listBox1.SelectedIndex;
            MessageBox.Show("您将给"+skList[ListIndex]+"用户发信息");
        }

        private void ZaiXianbutton_Click(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 发送震动 #@2@!
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ZhenDbutton_Click(object sender, EventArgs e)
        {
            String text = "#@2@!" + "给" + skList[ListIndex];
            byte[] by = Encoding.UTF8.GetBytes(text);
            sk.Send(by);
            SpeaktextBox.Text += "我：震动" + "\t发送给" + skList[ListIndex] + "\r\n";
        }
        /// <summary>
        /// 客户端震动代码实现
        /// </summary>
        void Zhendong() {
            for(int i = 0; i < 500; i++){
                this.Location = new Point(200, 200);
                this.Location = new Point(300, 300);
            }
        }
        /// <summary>
        /// 选择路径
        /// 并显示在label上
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void XuanzeFilebutton_Click(object sender, EventArgs e)
        {
            OpenFileDialog OFD = new OpenFileDialog();
            OFD.InitialDirectory = @"D:\C#project";
            OFD.Title = "请选择要传输的文件";
            OFD.Filter = "所有文件|*.*";
            OFD.ShowDialog();
            Filelabel.Text = OFD.FileName;
        }
        /// <summary>
        /// 实现发送文件功能
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void FasongfileButton_Click(object sender, EventArgs e)
        {
            String filePath = Filelabel.Text;
            using (FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read)) {
                byte[] buffer = new byte[1024 * 1024 * 5];
                int r = fs.Read(buffer,0,buffer.Length);
                List<byte> list = new List<byte>();
                list.Add(3);
                list.AddRange(Encoding.Default.GetBytes("("+(skList[ListIndex])+")"));
                list.AddRange(buffer);
                byte[] newbuffer = list.ToArray();
                sk.Send(newbuffer);
                SpeaktextBox.Text += "我：文件"+Filelabel.Text + "\t发送给" + skList[ListIndex] + "\r\n";
            }
        }
    }
}
